import { MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import ProForm, { ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import {
  Button,
  Collapse,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Space,
  Switch,
  TimePicker,
} from 'antd';
import type { CollapsibleType } from 'antd/lib/collapse/CollapsePanel';
import * as moment from 'moment';
import React, { useState } from 'react';
import type { AddBillItem, AddParkingRule } from '../data';
import styles from '../index.less';
import { addScheme } from '../service';

type billRuleModalProps = {
  setUnvisible: () => void;
  reloadFunc: () => void;
  visible: boolean;
};

const translateTimeToMin = (time?: moment.Moment) => {
  const temp = time ? moment(time) : moment();
  return temp.hour() * 60 + temp.minute();
};

const AddBillRule: React.FC<billRuleModalProps> = (props) => {
  const { reloadFunc, setUnvisible, visible } = props;
  const [disableService, setDisableService] = useState<CollapsibleType>('header');
  const [disablepreserving, setDisablepreserving] = useState<CollapsibleType>('header');
  const [disablePark, setDisablePark] = useState<CollapsibleType>('header');
  const [serviceSwitch, setServiceSwitch] = useState<boolean>(true);
  const [preservingSwitch, setPreservingSwitch] = useState<boolean>(true);
  const [parkSwitch, setParkSwitch] = useState<boolean>(true);
  const [parkNumber, setParkNumber] = useState<number>(0);
  const { Panel } = Collapse;

  const serviceFee = () => (
    <Switch
      defaultChecked
      checkedChildren="开启"
      unCheckedChildren="关闭"
      onChange={() => {
        if (serviceSwitch) {
          setServiceSwitch(false);
          setDisableService('disabled');
        } else {
          setServiceSwitch(true);
          setDisableService('header');
        }
      }}
    />
  );
  const preservingFee = () => (
    <Switch
      defaultChecked
      checkedChildren="开启"
      unCheckedChildren="关闭"
      onChange={async () => {
        if (preservingSwitch) {
          setPreservingSwitch(false);
          setDisablepreserving('disabled');
        } else {
          setPreservingSwitch(true);
          setDisablepreserving('header');
        }
      }}
    />
  );
  const parkFee = () => (
    <Switch
      defaultChecked
      checkedChildren="开启"
      unCheckedChildren="关闭"
      onChange={async () => {
        if (parkSwitch) {
          setParkSwitch(false);
          setDisablePark('disabled');
        } else {
          setParkSwitch(true);
          setDisablePark('header');
        }
      }}
    />
  );

  return (
    <Modal
      title="添加计费规则"
      visible={visible}
      width="1300px"
      destroyOnClose
      centered
      className={styles.addbillmodal}
      onCancel={() => {
        setUnvisible();
      }}
      okText={'提交'}
      footer={false}
    >
      <ProForm<AddBillItem>
        layout="horizontal"
        onFinish={async (value: AddBillItem) => {
          const { name, comment, service, preserving, Park } = value;
          const rules = [];
          if (serviceSwitch && service != undefined) {
            const serviceList = {
              pricing: service.pricing * 100 || 0,
            };
            rules.push({
              type: 'technical',
              ...serviceList,
            });
          }

          if (preservingSwitch && preserving != undefined) {
            const PreservingList = {
              hour: preserving?.hour * 100 || 0,
              pricing: preserving?.pricing * 100 || 0,
              price_unit: preserving?.price_unit || 0,
              free_time: preserving?.free_time || 0,
            };
            rules.push({
              type: 'space',
              ...PreservingList,
            });
          }
          if (parkSwitch && Park != undefined) {
            if (Park.length > 3) {
              message.error('禁止添加3条以上停车费信息');
            } else {
              const ParkFeeList = Park.map((item: AddParkingRule) => ({
                hour: item.hour * 100 || 0,
                pricing: item.pricing * 100 || 0,
                price_unit: item.price_unit || 0,
                free_time: item.free_time || 0,
                start_time: translateTimeToMin(item.duration?.[0]) || 0,
                end_time: translateTimeToMin(item.duration?.[1]) || 1440,
                max_price: (item.max_price || 0) * 100,
              }));
              for (let i = 0; i < Park.length; i++) {
                rules.push({
                  type: 'parking',
                  ...ParkFeeList[i],
                });
              }
            }
          }
          const values = {
            name,
            comment,
            rules,
          };

          const hide = message.loading('正在提交');
          try {
            const res = await addScheme(values);
            hide();
            if (res.success === true) {
              message.success('添加成功');
              reloadFunc();
              setUnvisible();
              return true;
            }
            message.error(`添加失败！${res.message}`);
            return false;
          } catch (error) {
            hide();
            message.error('添加失败！未知的错误！');
            return false;
          }
        }}
      >
        <ProFormText
          width={'xl'}
          name="name"
          label="规则名称"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入规则名称' }]}
        />
        <ProFormTextArea
          width={'xl'}
          name="comment"
          label="规则描述"
          placeholder="请输入"
          rules={[{ required: true, message: '请输入规则描述' }]}
        />
        <Collapse
          defaultActiveKey={['1']}
          collapsible={disableService}
          style={{ marginTop: 10, fontSize: 15 }}
        >
          <Panel header="服务技术费" key="1" extra={serviceFee()}>
            <Input.Group>
              <Form.Item
                label="费用单价"
                name={['service', 'pricing']}
                rules={[{ required: serviceSwitch, message: '请输入费用单价' }]}
              >
                <InputNumber min={0} precision={2} addonAfter={'元/次'} placeholder="请输入" />
              </Form.Item>
            </Input.Group>
          </Panel>
        </Collapse>
        <Collapse
          defaultActiveKey={['1']}
          collapsible={disablepreserving}
          style={{ marginTop: 10, fontSize: 15 }}
        >
          <Panel header="车位保留费" key="2" extra={preservingFee()}>
            <Input.Group compact>
              <Space>
                <Form.Item
                  label="免费时长"
                  name={['preserving', 'free_time']}
                  rules={[{ required: preservingSwitch, message: '请输入免费时长' }]}
                >
                  {/* 限制到0-60 */}
                  <InputNumber min={0} precision={2} addonAfter={'分钟'} placeholder="请输入" />
                </Form.Item>
                <Form.Item
                  label="首个计费周期"
                  name={['preserving', 'hour']}
                  rules={[{ required: preservingSwitch, message: '请输入首个计费周期费用' }]}
                >
                  <InputNumber min={0} precision={2} addonAfter={'元'} placeholder="请输入" />
                </Form.Item>

                <Form.Item label="费用单价" required={preservingSwitch}>
                  <Form.Item
                    name={['preserving', 'price_unit']}
                    noStyle
                    required={preservingSwitch}
                  >
                    <InputNumber
                      min={0}
                      addonAfter={'分钟'}
                      addonBefore={'每'}
                      placeholder="请输入"
                    />
                  </Form.Item>
                  <Form.Item
                    name={['preserving', 'pricing']}
                    noStyle
                    rules={[{ required: preservingSwitch, message: '' }]}
                  >
                    <InputNumber min={0} placeholder="请输入" precision={2} addonAfter={'元'} />
                  </Form.Item>
                </Form.Item>
              </Space>
            </Input.Group>
          </Panel>
        </Collapse>
        <Collapse
          defaultActiveKey={['1']}
          collapsible={disablePark}
          style={{ marginTop: 10, marginBottom: 20, fontSize: 15 }}
        >
          <Panel header="停车费" key="3" extra={parkFee()}>
            <span style={{ display: 'block', color: '#aaa', paddingBottom: '10px' }}>
              <i style={{ color: 'red' }}>*</i> 配置规则时间段(单位分钟)，请保证规则时间段覆盖00:00
              ~ 23:59，且无交叉时间段；
              <div style={{ paddingLeft: '0.6em' }}>全天请设置(00:00 - 00:00)</div>
            </span>
            <Form.List name="Park">
              {(fields, { add, remove }) => (
                <>
                  {fields.map((field, index) => (
                    <Space key={field.key} align={'baseline'} size={'small'}>
                      <Form.Item
                        {...field}
                        label={`规则时段${index + 1}`}
                        name={[field.name, 'duration']}
                        rules={[{ required: parkSwitch, message: '请输入' }]}
                      >
                        <TimePicker.RangePicker
                          format="HH:mm"
                          placeholder={['起始时间', '结束时间']}
                        />
                      </Form.Item>
                      <Form.Item {...field} label="计费" name={field.name} required={parkSwitch}>
                        <Input.Group>
                          <Form.Item
                            name={[field.name, 'price_unit']}
                            noStyle
                            rules={[{ required: parkSwitch, message: '请输入' }]}
                          >
                            <InputNumber
                              min={0}
                              addonBefore={'每'}
                              addonAfter={'分钟'}
                              style={{ width: '50%' }}
                            />
                          </Form.Item>
                          <Form.Item
                            name={[field.name, 'pricing']}
                            noStyle
                            rules={[{ required: parkSwitch, message: '' }]}
                          >
                            <InputNumber
                              precision={2}
                              min={0}
                              placeholder="金额"
                              addonAfter={'元'}
                              style={{ width: '50%' }}
                            />
                          </Form.Item>
                        </Input.Group>
                      </Form.Item>
                      <Form.Item
                        label="免费时长"
                        name={[field.name, 'free_time']}
                        rules={[{ required: parkSwitch, message: '请输入免费时长' }]}
                      >
                        {/* 限制到0-60 */}
                        <InputNumber
                          min={0}
                          precision={2}
                          addonAfter={'分钟'}
                          placeholder="请输入"
                        />
                      </Form.Item>
                      <Form.Item
                        {...field}
                        name={[field.name, 'max_price']}
                        label="最高收费"
                        rules={[{ required: parkSwitch, message: '请输入' }]}
                      >
                        <InputNumber precision={2} min={0} placeholder="金额" addonAfter={'元'} />
                      </Form.Item>
                      <MinusCircleOutlined
                        onClick={() => {
                          setParkNumber(parkNumber - 1);
                          const res = remove(field.name);
                          return res;
                        }}
                      />
                    </Space>
                  ))}
                  <Form.Item>
                    {parkNumber < 3 && (
                      <Button
                        type="dashed"
                        onClick={() => {
                          setParkNumber(parkNumber + 1);
                          const res = add();
                          return res;
                        }}
                        block
                        icon={<PlusOutlined />}
                      >
                        插入一个规则时段
                      </Button>
                    )}
                  </Form.Item>
                </>
              )}
            </Form.List>
          </Panel>
        </Collapse>
      </ProForm>
    </Modal>
  );
};
export default AddBillRule;
